package top.infopub.mgr.cap.web;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.infopub.dto.mkt.DetailTrackDto;
import top.infopub.dto.mkt.FundingApprovalDto;
import top.infopub.enums.cap.CapProcessDetailTypeEnum;
import top.infopub.enums.cap.FinancialInstitutionsLinkEnum;
import top.infopub.enums.cap.FinancialStyleEnum;
import top.infopub.enums.mkt.ProProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.FundingApprovalService;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.model.cap.*;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author Warking
 * @Date 2021/5/23 17:42
 * @Version 1.0  融资批复
 */
@Controller
@RequestMapping("/fundingApproval")
public class FundingApprovalController {
    @Autowired
    private FundingApprovalService fundingApprovalService;
    @Autowired
    private ProProcessManageService proProcessManageService;
    @Autowired
    private OAFlowService oaFlowService;
    @Autowired
    private CapProcessManageService capProcessManageService;


    /**
     * 融资批复详情跳转
     *
     * @return
     */
    @RequestMapping("/toDealOrDetail")
    public String toDealOrDetail(HttpServletRequest request, String setupFinancialId, String id, String proCode, String proName) {
        request.setAttribute("proCode", proCode);
        request.setAttribute("proName", proName);
        request.setAttribute("id", id);
        request.setAttribute("setupFinancialId", setupFinancialId);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        //
        FundingApproval fundingApproval = fundingApprovalService.selectByKey(id);
        if (fundingApproval != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), fundingApproval.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), fundingApproval.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(fundingApproval.getProcessId()) && fundingApproval.getProcessId().length() > 10) {
                request.setAttribute("processId", fundingApproval.getProcessId());
                String auditTabFlag = capProcessManageService.checkShowAuditTab(fundingApproval.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), fundingApproval.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        return "cap/lay-FinancialInstitutionApproval-detail";
    }


    /*融资批复列表接口*/
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<FundingApproval> queryDataByCondition(FundingApproval fundingApproval, ParamPage paramPage) throws ParseException {
        Page<FundingApproval> page = new Page();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //处理时间范围
        if (!StringUtils.isEmpty(fundingApproval.getDates())) {
            String[] splitTime = fundingApproval.getDates().split("~");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            fundingApproval.setStartDate(format.parse(splitTime[0]));
            fundingApproval.setEndDate(format.parse(splitTime[1]));
        }
        page = fundingApprovalService.selectPage(page, fundingApproval);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }


    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //立项审批
        capProcessManageService.auditProject(id, processId, status, auditMsg);
        return RspVo.getSuccessResponse();
    }

    /*金融机构审批环节枚举类*/
    @RequestMapping("/financialInstitutionsLink")
    @ResponseBody
    public List financingStyle() {
        List<Map<String, String>> list = FinancialInstitutionsLinkEnum.asList();
        return list;
    }

    /*__________________________________________________________________________________________*/
    /*批复结果详情 融资批复详情*/
    @RequestMapping("/queryDetail")
    @ResponseBody
    public FundingApprovalDto queryDetail(String setupFinancialId,String id) {
        FundingApprovalDto dto = new FundingApprovalDto();
        if (setupFinancialId != null && setupFinancialId != "") {
            dto = fundingApprovalService.queryDetailFundingApproval(setupFinancialId);
        } else {
            //审批会传id
            FundingApproval approval = fundingApprovalService.findByFundingApprovalId(id);
            /*dto.setFinancingApproval(approval);*/
            if (approval !=null)
            {
                dto = fundingApprovalService.queryDetailFundingApproval(approval.getSetupFinancialId());
            }
        }
        return dto;
    }

    //融资批复结果详情跟踪 保存提交  前端需要金融ID 和修改带ID 和proCode放到实体类
    @RequestMapping("/save")
    @ResponseBody
    public RspVo saveFundingApproval(String fundingApproval, String identifying, String id, String proCode, String financingTrackingDetail) {
        if (StringUtils.isEmpty(fundingApproval)) {
            return RspVo.getFailureResponse(0, "数据为空");
        }
        String o = StringEscapeUtils.unescapeJava(financingTrackingDetail);
        FinancingTrackingDetail f= JSON.parseObject(o, FinancingTrackingDetail.class);

        String object = StringEscapeUtils.unescapeJava(fundingApproval);
        FundingApproval Reply = JSON.parseObject(object, FundingApproval.class);
        if (!StringUtils.isEmpty(Reply.getId())) {
            //查询当前的跟踪数据的审批状态
            FundingApproval serviceApproval = fundingApprovalService.findByFundingApprovalId(Reply.getId());
            if (serviceApproval.getProcessStatus() == "1" || serviceApproval.getProcessStatus() == "9") {
                return RspVo.getFailureResponse(0, "审批中or审批终止，保存失败！");
            }
        }
        if ("0".equals(identifying)) {//0是保存
            int i = fundingApprovalService.saveFundingApproval(Reply);
            if (i > 0) {
                return RspVo.getSuccessResponse(0, "保存成功");
            } else {
                return RspVo.getFailureResponse(0, "保存失败");
            }
        } else {
            if (f == null || f.getFinancingTrackingList().size() != 18)
            {
                return RspVo.getFailureResponse(0, "金融机构审批环节缺少 提交失败");
            }
            /*注意 如果是修改审批状态 则是当前最新的融资报审的状态和主表的资料报审的审批状态一致*/
            //判断的状态
            FundingApproval serviceApproval = fundingApprovalService.findByFundingApprovalId(Reply.getId());
            if ("1".equals(serviceApproval.getProcessStatus()) || "9".equals(serviceApproval.getProcessStatus())) {
                return RspVo.getFailureResponse(0, "审批中或审批已完成，修改失败");
            }
            if (StringUtils.isNotBlank(serviceApproval.getOaId())) {
                oaFlowService.finishOA(serviceApproval.getOaId());
            }
            //提交流程  先保存
            int i = fundingApprovalService.saveFundingApproval(Reply);
            if (i > 0) {//保存成的情况 走流程
                //登录人员信息
                AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
                //发起流程
                String process = capProcessManageService.sendProcess(CapProcessDetailTypeEnum.PRO_NODE_TYPE7, object, id, proCode, vo);
                if (!StringUtils.isEmpty(process)) {
                    //有返回processID 证明提交成功 去往金融机构选择表和其子表写入数据
                    //写入前先判断 根据proCode 判断主表有没有数据
                    //不管主表有没有数据都要往从表添加数据
                    fundingApprovalService.saveToFinancialInstitutions(Reply);
                    return RspVo.getSuccessResponse(0, "提交成功");
                }
                return RspVo.getFailureResponse(0, "提交失败");
            } else { //提交-保存失败
                return RspVo.getFailureResponse(0, "提交失败");
            }
        }
    }
}
